<template>
  <van-button
    v-if="isFollowed"
    class="follow-btn"
    round
    :loading="followeLoading"
    size="small"
    @click="onFollow"
    >已关注</van-button
  >
  <van-button
    v-else
    class="follow-btn"
    type="info"
    color="#3296fa"
    round
    :loading="followeLoading"
    size="small"
    icon="plus"
    @click="onFollow"
    >关注</van-button
  >
</template>

<script>
import { addFollow, deleteFollow } from '@/api/user'

export default {
  name: 'FollowUser',
  components: {},
  model: {
    prop: 'isFollowed',
    event: 'update-isFollowed'
  },
  props: {
    isFollowed: {
      type: Boolean,
      required: true
    },
    userId: {
      type: [Number, String, Object],
      required: true
    }
  },
  data() {
    return {
      followeLoading: false
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    async onFollow() {
      this.followeLoading = true
      try {
        // 如果已关注，则取消关注
        const authorId = this.userId
        if (this.isFollowed) {
          await deleteFollow(authorId)
        } else {
          // 否则添加关注
          await addFollow(authorId)
        }
        // 更新视图
        this.$emit('update-isFollowed', !this.isFollowed)
      } catch (err) {
        if (err.response && err.response.status === 400) {
          this.$toast.fail('你不能关注你自己')
        }
        this.$toast.fail('操作失败')
      }
      this.followeLoading = false
    }
  }
}
</script>

<style scoped lang="less"></style>
